<template>
  <div class="upload-file">
    <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" v-model:file-list="fileList"
      :data="data" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed"
      :on-success="handleUploadSuccess" :on-remove="handleRemove" :show-file-list="true" :headers="headers"
      list-type="picture-card" class="upload-file-uploader" ref="fileUpload"
      :class="{ hide: fileList.length >= limit || disabled }" :accept="acceptTypes">

      <!-- 上传按钮 -->
      <div class="upload-card-content">
        <el-icon class="avatar-uploader-icon">
          <plus />
        </el-icon>
        <div v-if="title" class="upload-card-title">{{ title }}</div>
      </div>

      <!-- 自定义文件预览模板 -->
      <template #file="{ file }">
        <div class="file-card" @mouseenter="hoveredIndex = file.uid" @mouseleave="hoveredIndex = -1">
          <div class="file-card-content">
            <el-icon class="file-icon">
              <document />
            </el-icon>
            <div class="mb-2 text-12px leading-none">{{ title }}</div>
            <div class="file-name">{{ file.name }}</div>
          </div>
          <div v-if="hoveredIndex === file.uid && !disabled" class="file-overlay">
            <div class="file-actions">
              <el-icon size="28px" color="#fff" @click="handleRemove(file)" class="action-icon">
                <Delete />
              </el-icon>
              <!-- <el-icon v-if="showDownload" size="20px" color="#fff" @click="handleDownload(file)" class="action-icon">
                <Download />
              </el-icon> -->
            </div>
          </div>
        </div>
        <div v-if="showDownload" class="download-buttons mt-2">
          <el-button type="primary" size="small" @click="handleDownload(file)" :disabled="false">
            下载
          </el-button>
        </div>
      </template>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="props.showTip && !disabled">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>

  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick, getCurrentInstance } from 'vue'
import { getToken } from "@/utils/auth"
import Sortable from 'sortablejs'
import { Plus, Document, Delete, Download } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 上传接口地址
  action: {
    type: String,
    default: "/fang/common/file/upload"
  },
  // 上传携带的参数
  data: {
    type: Object
  },
  // 数量限制
  limit: {
    type: Number,
    default: 5
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 50
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["pdf", "jpg", "jpeg", "png"]
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 禁用组件（仅查看文件）
  disabled: {
    type: Boolean,
    default: false
  },
  // 拖动排序
  drag: {
    type: Boolean,
    default: true
  },
  // 是否显示下载按钮
  showDownload: {
    type: Boolean,
    default: false
  },
  // 文件用途说明
  title: {
    type: String,
    default: ''
  },
  // 是否显示提示信息
  showTip: {
    type: Boolean,
    default: true
  }
})

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const hoveredIndex = ref(-1)

const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + props.action) // 上传文件服务器地址

const headers = ref({ Authorization: "Bearer " + getToken() })
const fileList = ref([])
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
)

// 计算 accept 属性值
const acceptTypes = computed(() => {
  if (props.fileType && props.fileType.length > 0) {
    return props.fileType.map(type => `.${type}`).join(',')
  }
  return ''
})


watch(() => props.modelValue, val => {
  if (val) {
    let temp = 1
    // 首先将值转为数组

    fileList.value = val

  } else {
    fileList.value = []
    return []
  }
}, { deep: true, immediate: true })

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.')
    const fileExt = fileName[fileName.length - 1]
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确，请上传${props.fileType.join("/")}格式文件!`)
      return false
    }
  }
  // 校检文件名是否包含特殊字符
  if (file.name.includes(',')) {
    proxy.$modal.msgError('文件名不正确，不能包含英文逗号!')
    return false
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...")
  return true
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`)
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败")
  proxy.$modal.closeLoading()
}

// 上传成功回调
function handleUploadSuccess(res, file, fileList) {
  if (res.code === 200) {
    // 更新文件信息
    const fileIndex = fileList.findIndex(f => f.uid === file.uid)
    if (fileIndex > -1) {
      fileList[fileIndex] = {
        ...fileList[fileIndex],
        name: res.originalName,
        url: res.filePath,
        id: res.id,
        fileName: res.originalName,
        originalName: res.originalName,
        filePath: res.filePath,
        status: 'success'
      }
    }

    emit("update:modelValue", fileList)
    proxy.$modal.closeLoading()
  } else {
    proxy.$modal.closeLoading()
    proxy.$modal.msgError(res.msg)
    proxy.$refs.fileUpload.handleRemove(file)
  }
}

// 删除文件 - 使用Element Plus的on-remove事件
function handleRemove(file, fileList) {
  // Element Plus会自动更新fileList，我们只需要同步到父组件
  emit("update:modelValue", fileList)
}



// 下载文件
function handleDownload(file) {
  // 优先使用 url，如果没有则使用 filePath
  const fileUrl = file.url || file.filePath
  if (fileUrl) {
    // 创建一个临时的a标签来触发下载
    const link = document.createElement('a')
    link.href = fileUrl

    // 优先使用 originalName，如果没有则使用 name，最后使用 fileName
    const downloadName = file.originalName || file.name || file.fileName || 'download'
    link.download = downloadName

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } else {
    proxy.$modal.msgError('文件链接不存在')
  }
}


// 对象转成指定字符串分隔
function listToString____(list, separator) {
  let strs = ""
  separator = separator || ","
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : ''
}

// 初始化拖拽排序
onMounted(() => {
  if (props.drag && !props.disabled) {
    nextTick(() => {
      const element = proxy.$refs.fileUpload?.$el?.querySelector('.el-upload-list')
      if (element) {
        Sortable.create(element, {
          ghostClass: 'file-upload-darg',
          onEnd: (evt) => {
            const movedItem = fileList.value.splice(evt.oldIndex, 1)[0]
            fileList.value.splice(evt.newIndex, 0, movedItem)
            console.log("-------------onMounted")
            //emit('update:modelValue', listToString(fileList.value))
            emit('update:modelValue', fileList.value)
          }
        })
      }
    })
  }
})

</script>
<style scoped lang="scss">
.file-upload-darg {
  opacity: 0.5;
  background: #c8ebfb;
}

/* 上传组件样式 */

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
  transition: none !important;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

/* 上传卡片样式 */
.upload-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.upload-card-title {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  text-align: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.download-buttons {
  text-align: center;
}

/* 上传框尺寸 */
.upload-file-uploader :deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

.upload-file-uploader :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  // height: 100px;
  display: flex;
  flex-direction: column;
  border: none;
}

/* 隐藏上传按钮 */
.upload-file-uploader.hide :deep(.el-upload--picture-card) {
  display: none;
}

.upload-file-uploader :deep(.el-upload.el-upload--picture-card.is-disabled) {
  display: none !important;
}

/* 自定义文件预览样式 - 使用scoped-slot */
.file-card {
  position: relative;
  width: 100px;
  height: 100px;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  cursor: pointer;
}

.file-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 8px;
}

.file-icon {
  font-size: 32px;
  color: #409eff;
  margin-bottom: 8px;
}

.file-name {
  font-size: 12px;
  color: #606266;
  text-align: center;
  word-break: break-all;
  line-height: 1.2;
  max-width: 80px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.file-overlay:hover {
  background: rgba(0, 0, 0, 0.7);
}

.file-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
}

.action-icon {
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 4px;
  border-radius: 4px;
}

.action-icon:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}
</style>
